import { App } from 'antd'
import config from '@/config'
import { SiderItem } from '@/desktop/views/app'
import services from '@/services'
import { ReactComponent as SCRMIcon } from './scrm.svg'

export function SCRMNav({ collapsed }: { collapsed: boolean }) {
  const { modal } = App.useApp()

  const [status, setStatus] = useState<null | { url: string; hasDomain: boolean }>(null)
  useEffect(() => {
    if (config.DETECT_SCRM) void services.scrm.confirmStatus().then(setStatus)
  }, [])

  function go() {
    if (!status) return
    location.href = status.url
  }

  if (services.scrm.inSCRM || !config.DETECT_SCRM) return null

  let title: React.ReactNode
  let tooltip: React.ReactNode
  let openTooltip: React.ReactNode
  let onClick: () => void

  if (status === null) {
    title = '开启 SCRM'
    tooltip = null
    openTooltip = '尚未部署 SCRM'
    onClick = () => {
      modal.info({
        title: '开启 SCRM',
        content: <div style={{ padding: '20px 0' }}>尚未部署 SCRM 功能。</div>,
        okText: '确定',
      })
    }
  } else if (!status.hasDomain) {
    title = '开启 SCRM'
    tooltip = 'SCRM 尚未初始化，点此开始配置'
    openTooltip = 'SCRM 尚未初始化，点此开始配置'
    onClick = go
  } else {
    title = 'SCRM'
    tooltip = '进入 SCRM'
    openTooltip = '点此进入 SCRM'
    onClick = go
  }

  return <SiderItem
    className={collapsed ? 'collapsed' : ''}
    collapsed={collapsed}
    icon={<SCRMIcon />}
    title={title}
    tooltip={tooltip}
    openTooltip={openTooltip}
    onClick={onClick}
  />
}
